<?php
// 应用公共文件

//JSON返回方法
/**
 * @param $code
 * @param $message
 * @param array $data
 * @param array $page
 * @return false|string
 */
function ReJson($code, $message, $data = [], $page = [])
{
    return json_encode(
        [
            'code' => $code,
            'data' => $data,
            'message' => $message,
            'page' => $page
        ], JSON_UNESCAPED_UNICODE);

}

function intTostr($num, $str = '星期'): ?string
{
    // 判断是否为数组
    if (!is_numeric($num)) {
        return "要转换的金额只能为数字!";
    }
    // 预定义要转换的字符,自己可以切换一下要转换的方式
    // $arr = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    $arr = array('', '一', '二', '三', '四', '五', '六', '日');
    if ($num == 0) {
        $str = '';
    } elseif ($num == 9) {
        $str = '星期日';
    } else {
        $str .= $arr[$num];
    }
    return $str;
}

function intCapitalization($num): string
{
    $arr = array('零','一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二');
    return $arr[$num];
}

/**
 * 获取某月有几周
 * @param $date //查询月时间戳
 * @param $accurate //开始时间
 * @return int
 */
function weekOfMonth($date, $accurate = '')
{
    $dates = strtotime(date('Y-m-t', $date));

    if (empty($accurate)) {
        $accurate = strtotime(date("Y-m-01", $dates));
    }

    //Apply above formula.
    return weekOfYear($dates) - weekOfYear($accurate) + 1;
}

function weekOfYear($date)
{
    $weekOfYear = intval(date("W", $date));
    if (date('n', $date) == "1" && $weekOfYear > 51) {
        return 0;
    } else if (date('n', $date) == "12" && $weekOfYear == 1) {
        return 53;
    } else {
        return $weekOfYear;
    }
}

/**
 * 当前第几周
 * @return float|int
 */
function checker()
{
    $timestamp = time();  //任意日期时间戳
    $week = abs(ceil((date('j', $timestamp) - [0, 6, 5, 4, 3, 2, 1][date('w', strtotime(date('Y-m-01')))]) / 7));
    return $week;
}

/**
 * 获取某月周的起止时间
 * @param $month
 * @return array
 */
function get_weekinfo($month)
{
    $weeks = array_values(getWeeksInMonth($month));

    // 输出每个周的日期
    $data = [];
    foreach ($weeks as $weekNumber => $weekDates) {

        $data[$weekNumber]['start'] = $weekDates[0] . ' 00:00:00';
        $data[$weekNumber]['end'] = $weekDates[count($weekDates) - 1] . ' 23:59:58';

    }
    return $data;
}


function getWeeksInMonth($month)
{
    $weeks = [];

    // 创建指定月份的第一天
    $firstDayOfMonth = new DateTime($month . '-01');

    // 获取指定月份的最后一天
    $lastDayOfMonth = clone $firstDayOfMonth;
    $lastDayOfMonth->modify('last day of this month');

    // 创建DatePeriod对象，表示从第一天到最后一天的每一天
    $dates = new DatePeriod(
        $firstDayOfMonth,
        new DateInterval('P1D'),
        $lastDayOfMonth->modify('+1 day') // 将最后一天加1天以包含最后一天
    );

    // 遍历每一天，将其所在的周存入数组
    foreach ($dates as $date) {
        $weekNumber = $date->format('W'); // 获取当前日期所在的周
        $weeks[$weekNumber][] = $date->format('Y-m-d');
    }

    return $weeks;
}

/**
 * 数组转英文字母
 * 索引从0开始
 * @param $num
 * @return string
 */
function numberToLetter($num)
{
    $data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];
    return $data[$num];
}

function weekCapitalization($num): string
{
    $data = ['第一周', '第二周', '第三周', '第四周', '第五周', '第六周', '第七周'];
    return $data[$num];
}

function weekCapitalizationKey($name): string
{
    $data = ['第一周', '第二周', '第三周', '第四周', '第五周', '第六周', '第七周'];
    return array_search($name, $data, true);
}

function week($name)
{
    $data = ['weekend', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    return $data[$name];
}

function htmlField($ks)
{
    $data = ['Mon', 'Tue', 'Thu', 'Fri', 'Sat', 'Wed'];
    return $data[$ks];
}

/**
 * 树状结构
 * @param $list
 * @param $pk
 * @param $pid
 * @param $child
 * @param $root
 * @param $rules
 * @return array
 */
function Tree($list, $pk = 'd_id', $pid = 'pid', $child = 'childs', $root = 0, $rules = [])
{
    // 创建Tree
    $tree = [];
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            if ($data instanceof \think\Model) {
                $list[$key] = $data->toArray();
            }
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            if (!isset($list[$key][$child])) {
//                $list[$key][$child] = [];
            }
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

function handlePersonIds($uid_person_ids, $person_ids, $flag = false)
{
    sort($uid_person_ids);
    sort($person_ids);
    if (count($person_ids) == 1 && $person_ids[0] == 0) {
        $person_ids = [];
    }
    if (!$uid_person_ids || !$person_ids) {
        $person_ids = [0];
    } elseif ($uid_person_ids && !$person_ids) {
        $person_ids = $uid_person_ids;
    } elseif (!$uid_person_ids && $person_ids) {
        $person_ids = $uid_person_ids;
    } elseif ($uid_person_ids && $person_ids) {
        if (count($person_ids) == 1 && $person_ids[0] == 0 && !$flag) {
            $person_ids = $uid_person_ids;
        } else {
            $person_ids = array_intersect($person_ids, $uid_person_ids);
        }
    }
    return $person_ids;
}

function serviceHandlePersonIds($enter_ids, $other_ids)
{
    if (!$enter_ids || !$other_ids) {
        return [];
    }
    if ($enter_ids && $other_ids) {
        $enter_ids = array_intersect($enter_ids, $other_ids);
    } elseif ($enter_ids && !$other_ids) {
        $enter_ids = [];
    } elseif (!$enter_ids && $other_ids) {
        $enter_ids = array_intersect($enter_ids, $other_ids);
    } elseif (!$enter_ids && !$other_ids) {
        $enter_ids = [];
    }
    return $enter_ids;
}

function flagStatus($param)
{
    //判断参数是否有值
    $flag = false;
    $key_arr = [
        'aliasId',
        'page',
        'pageNum',
        'user_login_id',
    ];
    foreach ($param as $key => $item) {
        if (in_array($key, $key_arr)) {
            continue;
        }
        if ($item) {
            $flag = true;
            break;
        }
    }
    return $flag;
}


/**
 * 数据分页
 * @param $data
 * @param $page
 * @param $pageNum
 * @param string $sortField
 * @param string $field
 * @param bool $sort
 * @return array
 */
function page($data, $page, $pageNum, string $sortField = 'desc', string $field = 'create_date', bool $sort = true): array
{
    /**
     * 去除data空值
     */
    foreach ($data as $k => $datum) {
        if (!$datum){
            unset($data[$k]);
        }
    }
    $data = array_values ($data);

    //false 不排序
    if (!$sort){
        return array_slice(ChargeBackDataList($data), ($page - 1) * $pageNum, $pageNum);
    }

    if ($sortField == 'desc') {
        //先排序 再把退单与退单完成放一起
        $re = my_sort($data, $field, SORT_DESC);
    } else {
        //先排序 再把退单与退单完成放一起
        $re = my_sort($data, $field);
    }
    return array_slice(ChargeBackDataList($re), ($page - 1) * $pageNum, $pageNum);
}

//通过某个日期段内的周几获取对应的日期  开始日期 结束日期
/**
 * @param //data 日期 array(start_date,end_data)
 */
function getDateByWeek($data)
{
    $start_date = strtotime($data['start_date']);
    $end_date = strtotime($data['end_date']);
    $days = ($end_date - $start_date) / 86400;
    $weekArr = array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
    $newDate = array();
    // 组建数组格式 $dataWeek['日期'] => 星期
    for ($i = 0; $i < $days; $i++) {
        $num_week = date('w', $start_date + ($i * 86400));
        $dateWeek[date('Y-m-d', $start_date + ($i * 86400))] = $weekArr[$num_week];
    }
    // 查找两个数组的交集，即获取提交的星期对应的日期
    $newDate = array_intersect($dateWeek, $data['items']);
    // 获取数组中的键值(日期)，并组成一个新数组
    return array_keys($newDate);
}

/**
 * 获取月内某一周开始结束时间
 * @param $num
 * @return mixed
 */
function getWeekDetails($num)
{
    $moonStart = date('Y-m') . '-1';
    //判断给定日期是周几
    $dateW = date('w', strtotime($moonStart));
    if ($dateW == 0) {
        $dateW = 7; //周日
    }
    $moonEnd = date('Y-m') . '-' . (8 - $dateW);

    $data[0]['start'] = $moonStart;
    $data[0]['end'] = $moonEnd;

    $moonStart2 = date('Y-m') . '-' . (date('d', strtotime($moonEnd)) + 1);

    $moonEnd2 = date('Y-m') . '-' . (date('d', strtotime($moonStart2)) + 6);

    $data[1]['start'] = $moonStart2;
    $data[1]['end'] = $moonEnd2;

    $moonStart3 = date('Y-m') . '-' . (date('d', strtotime($moonEnd2)) + 1);

    $moonEnd3 = date('Y-m') . '-' . (date('d', strtotime($moonStart3)) + 6);
    $data[2]['start'] = $moonStart3;
    $data[2]['end'] = $moonEnd3;

    $moonStart4 = date('Y-m') . '-' . (date('d', strtotime($moonEnd3)) + 1);

    $moonEnd4 = date('Y-m') . '-' . (date('d', strtotime($moonStart4)) + 6);
    $data[3]['start'] = $moonStart4;
    $data[3]['end'] = $moonEnd4;

    $lastday = date('Y-m-d', strtotime("$moonStart +1 month -1 day"));

    $day = (strtotime($lastday) - strtotime($moonEnd4)) / 86400;

    if ($day > 7) $day = 7;

    if ($day > 0) {
        $moonStart5 = date('Y-m') . '-' . (date('d', strtotime($moonEnd4)) + 1);

        $moonEnd5 = date('Y-m') . '-' . (date('d', strtotime($moonStart5)) + $day - 1);
        $data[4]['start'] = $moonStart5;
        $data[4]['end'] = $moonEnd5;
    }

    $days = (strtotime($lastday) - strtotime($moonEnd5)) / 86400;

    if ($days > 0) {
        $moonStart6 = date('Y-m') . '-' . (date('d', strtotime($moonEnd5)) + 1);

        $moonEnd6 = date('Y-m') . '-' . (date('d', strtotime($moonStart6)) + $days - 1);

        $data[5]['start'] = $moonStart6;
        $data[5]['end'] = $moonEnd6;
    }

    return $data[$num];
}

/**
 * 对数据进行排序
 * @param $arrays
 * @param $sort_key
 * @param $sort_order
 * @param $sort_type
 * @return array|false
 */
function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
{
    if (!$arrays) {
        return [];
    }
    if (is_array($arrays)) {
        foreach ($arrays as $array) {
            if (is_array($array)) {
//                if (!isset($array[$sort_key])) {
//                    return $arrays;
//                }
                if (!isset($array[$sort_key])) {
                    if (isset($array['create_date'])){
                        $array[$sort_key] = strtotime($array['create_date']);
                    }else{
                        return $arrays;
                    }
                }else{
                    if ($sort_key === 'sale_date' || $sort_key === 'submit_date' || $sort_key === 'transaction_date' || $sort_key === 'create_date'|| $sort_key === 'examine_date'){
                        $array[$sort_key] = strtotime($array[$sort_key]);
                    }
                }

//                if ($sort_key === 'create_date') {
//
//                    $array[$sort_key] = strtotime($array[$sort_key]);
//                }
                $key_arrays[] = $array[$sort_key];
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
    array_multisort($key_arrays, $sort_order, $sort_type, $arrays);

    return ChargeBackDataList($arrays);
}

function getUserInfo($token = '')
{
    if (!$token) {
        $token = request()->header('token');
    }
    $userInfo = \think\facade\Cache::store('file')->get(md5($token));
    if ($userInfo) {
        return $userInfo;
    } else {
        return [];
    }
}

// 验证手机号码
function isMobile($mobile): bool
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return (bool)preg_match('/^1[0123456789]\d{9}$/', $mobile);
}

/**
 * 去除二维数组重复值
 */
function assoc_unique($arr, $key)
{
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}

/**
 * 校验json字符串
 * @param string $stringData
 * @return bool
 */
function isJsonString($stringData)
{
    if (empty($stringData)) return false;

    try {
        //校验json格式
        json_decode($stringData, true);
        return JSON_ERROR_NONE === json_last_error();
    } catch (\Exception $e) {
        return false;
    }
}

/**
 * 按规则排序完成，如果是退单数据则把退单完成与退单数据放一起
 */
function ChargeBackDataList($data)
{
    $descData = array_reverse($data);

    $arrId = array_column($descData, 'id');

//    $arrCreateDate = array_column($descData, 'create_date');

    $datas = [];

    foreach ($data as $k => $datum) {
        if (!isset($datum['status'])) {
            $datas[] = $datum;
            continue;
        }
        if ($datum['status']['id'] == 999) { //退单完成ID为999
            $datas[] = $datum;
            //寻找已退单关联数据
            //添加退单信息
            $y = $descData[array_search($datum['id'], $arrId)];
            if ($y['status']['id'] != 999) {
                $datas[] = $y;
            }
            continue;
        }
        if ($datum['status']['text'] == '已退单') { //如果是已退单
//            $datasIdArr = array_column ($datas,'id');
//            if (in_array ($datum['id'],$datasIdArr)){
//                continue;
//            }

            foreach ($datas as $item) {
                if ($item['id'] == $datum['id'] && $item['certificate_code'] == $datum['certificate_code']) {
                    if ($item['status']['id'] == $datum['status']['id']) {
                        continue 2;
                    }
                }
            }
        }

        $datas[] = $datum;
    }

    return $datas;
}

/**
 * 处理起止时间
 * @param $type //快速筛选 1-今日 2-本周 3-当月 4-本季度 5-本年
 * @param $startDate //开始日期
 * @param $endDate //结束日期
 * @return array|string[]
 */
function handleStartStopDate($type, $startDate, $endDate)
{
    //默认初始化为今日起止狮山
    $suffix_start = ' 00:00:00';
    $suffix_end = ' 23:59:59';
    $dateArray = [
        'startDate' => date('Y-m-d') . $suffix_start,
        'endDate' => date('Y-m-d') . $suffix_end
    ];
    //如果快速获取时间 和 开始时间截止时间都存在拿取当前传入的时间
    //或
    //快速获取时间不存在并且开始时间截止时间都存在拿取当前传入的时间
    if (($type && $startDate && $endDate) || (!$type && $startDate && $endDate)) {
        $dateArray['startDate'] = $startDate . $suffix_start;
        $dateArray['endDate'] = $endDate . $suffix_end;
    } elseif ($type && !$startDate && !$endDate) {
        switch ($type) {
            case 2://本周
                $dateArray = getWeekTime();
                break;
            case 3://当月
                $dateArray =  getMonthTime();
                break;
            case 4://本季度
                $dateArray =  getQuarterTime();
                break;
            case 5://本年
                $dateArray =  getYearTime();
                break;
        }
    }
    return $dateArray;
}

/**
 * 获取本周时间
 * @return string[]
 */
function getWeekTime()
{
    // 获取当前日期
    $currentDate = date('Y-m-d');
    // 获取本周起始日期
    $weekStart = date('Y-m-d', strtotime('this week', strtotime($currentDate)));
    // 获取本周结束日期
    $weekEnd = date('Y-m-d', strtotime('this week +6 days', strtotime($currentDate)));
    $start_time = $weekStart . ' 00:00:00';
    $end_time = $weekEnd . ' 23:59:59';
    return [
        'startDate' => $start_time,
        'endDate' => $end_time
    ];
}


//获取本月起止时间
function getMonthTime()
{
    // 获取当前日期
    $currentDate = date('Y-m-d');
    // 获取本月起始日期
    $monthStart = date('Y-m-01', strtotime($currentDate));
    // 获取本月结束日期
    $monthEnd = date('Y-m-t', strtotime($currentDate));
    $start_time = $monthStart . ' 00:00:00';
    $end_time = $monthEnd . ' 23:59:59';
    return [
        'startDate' => $start_time,
        'endDate' => $end_time
    ];
}

/**
 * 获取本季度起止时间
 * @return array
 */
function getQuarterTime()
{
    $season = ceil((date('n'))/3);//当月是第几季度
    $start = date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y')));
    $end = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')));
    return [
        'startDate' => $start,
        'endDate' => $end
    ];
}

/**
 * 获取本年起止时间
 * @return array
 */
function getYearTime()
{
    $suffix_start = ' 00:00:00';
    $suffix_end = ' 23:59:59';
    $currentYear = date('Y');
    // 获取本年度起始时间
    $dateArray['startDate'] = date('Y-01-01', strtotime($currentYear)) . $suffix_start;
    // 获取本年度结束时间
    $dateArray['endDate'] = date('Y-12-31', strtotime($currentYear)) . $suffix_end;
    return $dateArray;
}
/**
 * 判断是否是一维数组
 * @param $array
 * @return bool
 */
function is_one_dimensional_array($array): bool
{
    foreach ($array as $value) {
        if (is_array($value)) {
            return false;
        }
        return true;
    }
    return true;
}
//返回随机字符串
function RandAbc($length=""){
    $str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    return str_shuffle($str);
}
